/**
 * MCP测试工具函数
 * 提供共享的测试设置和工具，减少代码重复
 */

const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { InMemoryTransport } = require('@modelcontextprotocol/sdk/inMemory.js');
const { Client } = require('@modelcontextprotocol/sdk/client/index.js');
const { ListToolsRequestSchema, CallToolRequestSchema } = require('@modelcontextprotocol/sdk/types.js');

/**
 * 创建测试MCP服务器
 */
function createTestServer() {
    const server = new Server(
        { name: 'test-vision-analyzer', version: '2.0.0-test' },
        { capabilities: { tools: { listChanged: true } } }
    );

    // Mock分析函数
    const { analyze_image, compare_image, analyze_design_screenshot, list_models, use_model, compare_image_with_bounding_boxes, extract_component_hierarchy, get_exact_layout_specifications, identify_visual_tokens, analyze_design_with_precision } = require('../../analyze.js');

    // 注册工具列表处理器
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
        tools: [
            {
                name: 'analyze_image',
                description: 'Analyze images with AI vision models',
                inputSchema: {
                    type: 'object',
                    properties: {
                        image: { type: 'string', description: 'Base64 encoded image' },
                        prompt: { type: 'string', description: 'Analysis prompt' }
                    },
                    required: ['image', 'prompt']
                }
            },
            {
                name: 'compare_image',
                description: 'Compare two images',
                inputSchema: {
                    type: 'object',
                    properties: {
                        image1: { type: 'string', description: 'First base64 encoded image' },
                        image2: { type: 'string', description: 'Second base64 encoded image' },
                        prompt: { type: 'string', description: 'Comparison prompt' }
                    },
                    required: ['image1', 'image2', 'prompt']
                }
            },
            {
                name: 'list_models',
                description: 'List available models',
                inputSchema: {
                    type: 'object',
                    properties: {}
                }
            },
            {
                name: 'use_model',
                description: 'Switch to a specific model',
                inputSchema: {
                    type: 'object',
                    properties: {
                        provider: { type: 'string', description: 'Provider name' },
                        model: { type: 'string', description: 'Model name' }
                    },
                    required: ['provider', 'model']
                }
            }
        ]
    }));

    // 注册工具调用处理器
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;

        try {
            switch (name) {
                case 'analyze_image':
                    const result = await analyze_image(args.image, args.prompt);
                    return { content: [{ type: 'text', text: result }] };

                case 'compare_image':
                    const comparisonResult = await compare_image(args.image1, args.image2, args.prompt);
                    return { content: [{ type: 'text', text: comparisonResult }] };

                case 'list_models':
                    const models = await list_models();
                    return { content: [{ type: 'text', text: JSON.stringify(models) }] };

                case 'use_model':
                    const modelResult = await use_model(args.provider, args.model);
                    return { content: [{ type: 'text', text: JSON.stringify(modelResult) }] };

                default:
                    throw new Error(`Unknown tool: ${name}`);
            }
        } catch (error) {
            return {
                content: [{ type: 'text', text: `Error: ${error.message}` }],
                isError: true
            };
        }
    });

    return server;
}

/**
 * 设置MCP客户端和服务器连接
 */
async function setupMCPConnection() {
    const server = createTestServer();
    const client = new Client(
        { name: 'test-client', version: '1.0.0' },
        { capabilities: {} }
    );

    // 创建内存传输对
    const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();

    await server.connect(serverTransport);
    await client.connect(clientTransport);

    return { server, client, serverTransport, clientTransport };
}

/**
 * 清理MCP连接
 */
async function cleanupMCPConnection(server, client, serverTransport, clientTransport) {
    try {
        if (client) await client.close();
        if (server) await server.close();
    } catch (error) {
        console.warn('Error during cleanup:', error.message);
    }
}

module.exports = {
    createTestServer,
    setupMCPConnection,
    cleanupMCPConnection
};